package com.hliushi.oauth2.exception;


import com.hliushi.oauth2.response.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @ClassName GlobalExceptionHandler
 * @Description 处理系统异常
 * @Author hliushi
 * @Date 2021/7/7 8:21
 * @Version V1.0
 **/
@ControllerAdvice
@ResponseBody   // 该注解是为异常处理完之后给调用方输出一个json格式的封装数据
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 缺少请求参数异常
     * 参数缺失的时候, 会抛出HttpMessageNotReadableException, 我们可以拦截该异常，做一个友好处理
     *
     * @param ex HtpMessageNotReadableException
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public JsonResult<Void> handleParameterNotReadableException(MissingServletRequestParameterException ex) {

        LOGGER.error("缺少请求参数, {}", ex.getMessage());

        return new JsonResult<>("400", "缺少必要的请求参数");
    }


    /**
     * NPE空指针异常
     *
     * @param npe NullPointerException
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public JsonResult<Void> handleTypeMismatchException(NullPointerException npe) {

        LOGGER.error("空指针异常, {}", npe.getMessage());
        return new JsonResult<>("500", "空指针异常了");
    }


    /**
     * 拦截业务异常, 返回业务异常信息
     *
     * @param
     * @return
     */
    @ExceptionHandler(BusinessErrorException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public JsonResult<Void> handleBusinessError(BusinessErrorException ex) {
        String code = ex.getCode();
        String message = ex.getMessage();

        return new JsonResult<>(code, message);
    }


    /**
     * 系统异常, 预期以外异常
     * #
     * 拦截Exception虽然可以一劳永逸, 但是不利于我们去排查或者定位问题
     * 实际项目中, 可以把拦截Exception异常写在GlobalExceptionHandler最下面 [猜测方法在类中的顺序, 与拦截顺序有关]
     * 如果没有找到, 最后再拦截一下Exception, 保证输出信息友好
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public JsonResult<Void> handleUnexpectedServer(Exception ex) {

        LOGGER.error("系统异常: ", ex);

        return new JsonResult<>("500", "系统发生异常, 请联系管理员");
    }

}
